package de.berlani.geolike;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONServerLink implements ServerLink{
		
	private static String url = "http://berlani.de/geolike/recievegeo.php";
	
	public HttpResponse doPostJson(JSONObject c) throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        HttpEntity entity;
        StringEntity s = new StringEntity(c.toString());
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        entity = s;
        request.setEntity(entity);
        HttpResponse response;
        response = httpclient.execute(request);
        return response;
    }
	
	public void Send(Map<String,String> m) throws ClientProtocolException, IOException{
		if(m != null && m.isEmpty() == false){
			JSONObject j = new JSONObject();
			String k, v;
			Iterator<String> itKeys = m.keySet().iterator();
			while(itKeys.hasNext()){
				k = itKeys.next();
				v = m.get(k);
				try{
					j.put(k,v);
				}catch(JSONException e){
					e.printStackTrace();
				}
			}
			doPostJson(j);
		}
	}
}